import React, { useState, useEffect } from 'react';
import { Form, Button, message, Select, Card, Switch , Modal, Input, Checkbox, Radio } from 'antd';
import { history, connect, ConnectProps, Dispatch } from 'umi';
import { ExclamationCircleOutlined, InfoCircleFilled, CloseOutlined, ArrowLeftOutlined, CopyOutlined } from '@ant-design/icons'
import { FORM_LAYOUT } from '@/utils/const';
import { getTypes, addEdgeNode, getScripts, getDownload } from './service';
import SyntaxCopy from '@/components/InfoShow/SyntaxCopy';
import trans from '@/utils/translate';
import { PageContainer } from '@ant-design/pro-layout';
import { edgeRequest } from '@/utils/request';
import { NodeStateType } from './model';
import { nameRule } from '@/utils/rule';
interface node {
  name: string,
  describe?: string,
  nodeType: string,
  type: string,
  deviceSeries: string,
};
interface Props extends ConnectProps {
  dispatch: Dispatch;
  node: NodeStateType;
}
const { Option } = Select;
const { Group } = Radio;
const Add: React.FC<Props> = (props) => {
  const { dispatch } = props;
  const [next, setNext] = useState(false);
  const [form] = Form.useForm();
  const [codes, setCodes] = useState(['', '', '', '']); // 安装脚本数组
  const [codeUzip, setCodeUzip] = useState('');
  const [codeInstall, setCodeInstall] = useState('');
  const [hasRead, setHasRead] = useState(false);
  const [types, setTypes] = useState([]);
  const [nodeId, setNodeId] = useState('');
  const [hasDownload, setHasDownload] = useState(false);
  const [showSeries, setShowSeries] = useState(false);
  const accelerateOptions = [
    {label: trans('nodeManagement.edgeNode.addEdgeNode.noAIAccelerate'), value: ''},
    {label: trans('nodeManagement.edgeNode.addEdgeNode.huaweiAIAccelerate'), value: 'huawei'},
    {label: trans('nodeManagement.edgeNode.addEdgeNode.NvidiaGPU'), value: 'nvidiaGPU'},
  ];
  const huaweiOptions = [
    {label: 'Ascent310', value: 'a310'},
    {label: 'Ascent910', value: 'a910'},
  ];
  const jumpNext = (values: node) => {
    // 如果没有节点ID就创建节点
    if (!nodeId) {
      const { describe, name, nodeType, type, deviceSeries } = values;
      const params = {
        describe,
        nodeType,
        nodeName: name,
        type,
        deviceSeries,
      };
      addEdgeNode(params).then(res => {
        if (res && res.code === 0) {
          setNodeId(res.data.nodeId);
          setScripts(name, res.data.nodeId);
          setNext(true);
        }
      })
    } else {
      setNext(true);
    }
  }
  const { location } = props;
  const { down, id, name } = location?.query as { down: boolean, id: string, name: string};
  console.log(down, id, name);
  const setScripts = (name: string, nodeId: string, arch: string = 'arm64') => {
    const params = {
      nodeId,
      nodeName: name,
      arch
    }
    getScripts(params).then(res => {
      if (res && res.code === 0) {
        const { script } = res.data;
        console.log(script)
        setCodes(script);
        console.log(codes);
        setCodeUzip(script[0]);
        setCodeInstall(script[1]);
      }
    })
  };
  const nodeTypes = [
    { label: 'HUAWEI_NPU', value: 'npu' },
    { label: 'HUAWEI_NPU', value: 'npu' },
    { label: 'HUAWEI_NPU', value: 'npu' },
  ]
  const Item = Form.Item;
  useEffect(() => {
    console.log(id);
    if (id) {
      setNodeId(id);
      setHasDownload(Boolean(down));
      setNext(Boolean(down));
      setScripts(name, id);
    } else {
      getTypes().then(res => {
        if (res && res.code === 0) {
          setTypes(res.data.nodeTypes);
        }
      })
    }
  }, [])

  return (
    <PageContainer
      onBack={() => {
        hasDownload ? history.push('/node-management/edge-node') :
        Modal.confirm({
          centered: true,
          closable: true,
          icon: <ExclamationCircleOutlined />,
          maskClosable: true,
          okType: 'danger',
          okText: '确认',
          cancelText: '取消',
          width: '30%',
          title: <div style={{ fontWeight: 'bold' }}>确定退出么？</div>,
          content: <div>当前页面的数据不会保存</div>,
          onOk: async () => {
            dispatch({ type: 'node/setTab', payload: { tab: 'single' }})
            history.push('/node-management/edge-node');
          },
          cancelButtonProps: {},
          onCancel: () => {},
        });
      }}
    >
      {/* 第一步，点击下一步会先创建节点，获取到 nodeId，然后到下一步 */}
      { !next &&
        <Card>
          <Form
            form={form}
            onFinish={(values) => jumpNext(values)}
            {...FORM_LAYOUT}
          >
            <Item
              label={trans('nodeManagement.edgeNode.nodeName')}
              name='name'
              rules={nameRule()}
            >
              <Input></Input>
            </Item>
            <Item
              label={trans('nodeManagement.edgeNode.describe')}
              name='describe'
            >
              <Input.TextArea autoSize={{minRows:3}} placeholder='请输入描述，限制 200 字符以内' maxLength={200} showCount />
            </Item>
            <Item
              label={trans('nodeManagement.edgeNode.nodeType')}
              rules={[{ required: true, message: '请选择节点类型' }]}
              name='nodeType'
            >
              <Select>
                {
                  types?.map(item => <Option value={item} key={item}>{item}</Option>)
                }
              </Select>
            </Item>
            <Item
              label={trans('nodeManagement.edgeNode.addEdgeNode.AIAccelerate')}
              name='type'
            >
              <Radio.Group
                options={accelerateOptions}
                defaultValue={''}
                onChange={(e)=>{
                  setShowSeries(e.target.value === 'huawei');
                  form.setFieldsValue({
                    deviceSeries: huaweiOptions[0].value,
                  });
                }}
                optionType="button"
                buttonStyle="solid"
              />
            </Item>
            {showSeries && <Item
              wrapperCol={{ offset: 4, span: 16 }}
              label=''
              name='deviceSeries'
            >
              <Radio.Group
                options={huaweiOptions}
                optionType="button"
                buttonStyle="solid"
              />
            </Item>}
            <Item wrapperCol={{ offset: 4, span: 16 }}>
              <Button type='primary' htmlType='submit'>{trans('common.next')}</Button>
            </Item>
          </Form>
        </Card>
      }
      { next &&
        <Card style={{position: 'relative'}}>
          {/* {!id && <Button type='text' onClick={() => setNext(false)}><ArrowLeftOutlined />返回上一步</Button>} */}
          <Button type='text' style={{position: 'absolute', right: 4, top: 4}} href='./' icon={<CloseOutlined />} ></Button>
          <article style={{textAlign: 'center'}}>
            <h1 style={{fontSize:'20px', fontWeight:'bold'}}>{trans('nodeManagement.edgeNode.addEdgeNode.title')}</h1>
            <p>{trans('nodeManagement.edgeNode.addEdgeNode.subTitle')}</p>
            {!Boolean(id) &&
            <p>
              {trans('nodeManagement.edgeNode.addEdgeNode.tip')}
              <strong>{trans('nodeManagement.edgeNode.addEdgeNode.strongTip')}</strong>
            </p>}
            <Card style={{margin: '0 10%', background: '#ececec'}}>
              <section>
                {trans('nodeManagement.edgeNode.addEdgeNode.settingDoc')}：
                <Button
                  style={{marginLeft:'30px'}}
                  type='primary'
                  // disabled={hasDownload}
                  disabled={Boolean(id)}
                  danger
                  onClick={()=>setHasDownload(true)}
                >
                  <a download='cert.tar.gz' href={`${getDownload}/${nodeId}?token=${localStorage.getItem('token')}`}>
                    {trans('nodeManagement.edgeNode.addEdgeNode.downloadDoc')}
                  </a>
                </Button>
                <section style={{textAlign: 'left'}}>
                  <h2>{trans('nodeManagement.edgeNode.addEdgeNode.guide')}</h2>
                  {/* <Item label={trans('nodeManagement.edgeNode.addEdgeNode.nodeTypeSelect')} required>
                    <Select></Select>
                  </Item> */}
                  <h5><InfoCircleFilled style={{color: '#1890FF'}}/>{trans('nodeManagement.edgeNode.addEdgeNode.step')}</h5>
                  <SyntaxCopy
                    code={codes[0]}
                    step={trans('nodeManagement.edgeNode.addEdgeNode.stepOne')} />
                  <SyntaxCopy
                    code={codes[1]}
                    step={trans('nodeManagement.edgeNode.addEdgeNode.stepTwo')} />
                  <strong>{trans('nodeManagement.edgeNode.addEdgeNode.stepThree')}</strong>
                  <div style={{margin: ' 5px 0 0 30px'}}>
                    <SyntaxCopy
                      code={codes[2]}
                      step={trans('nodeManagement.edgeNode.addEdgeNode.stepThree.a')} />
                    <SyntaxCopy
                      code={codes[3]}
                      step={trans('nodeManagement.edgeNode.addEdgeNode.stepThree.b')} />
                    <span>{trans('nodeManagement.edgeNode.addEdgeNode.stepThree.tip')}</span>
                  </div>
                </section>
                {
                  !down &&
                  <section style={{textAlign: 'right'}}>
                    <Checkbox checked={hasRead} onChange={()=> setHasRead(!hasRead)}>
                      {trans('nodeManagement.edgeNode.addEdgeNode.checkDownload')}
                    </Checkbox>
                    <Button
                      type='primary'
                      disabled={!hasRead || !hasDownload}
                      onClick={() => {
                        dispatch({ type: 'node/setTab', payload: { tab: 'single' }})
                        history.push('/node-management/edge-node')}
                      }
                    >
                      {trans('nodeManagement.edgeNode.addEdgeNode.over')}
                    </Button>
                  </section>
                }
              </section>
            </Card>
          </article>
        </Card>
      }
    </PageContainer>
  )
}

export default connect(({ node }: { node: NodeStateType }) => ({
  node,
}))(Add);
